<script setup>
import {
  articleAddChannelService,
  articleEditChannelService
} from '@/api/article'
import { ref } from 'vue'
const dialogVisible = ref(false) // 控制弹窗显示
const formRef = ref() // 获取表单实例
const emit = defineEmits(['refreshList'])
// 表单数据
const formModel = ref({
  cate_name: '',
  cate_alias: ''
})
// 表单验证规则
const rules = {
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '分类名必须是1-10位的非空字符',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类别名必须是1-15位的字母数字',
      trigger: 'blur'
    }
  ]
}
// 打开弹窗方法
//    openDialog({}) 空参数说明添加功能
//    openDialog({id:1}) 说明是修改功能，表单需要渲染数据
const openDialog = async (row) => {
  dialogVisible.value = true //打开弹窗
  console.log(row)
  formModel.value = { ...row }
}
// 提交方法
const onSubmit = async () => {
  await formRef.value.validate() // 验证表单
  if (formModel.value.id) {
    await articleEditChannelService(formModel.value)
    ElMessage.success('修改成功')
  } else {
    await articleAddChannelService(formModel.value)
    ElMessage.success('添加成功')
  }
  // 通知父组件刷新页面
  emit('refreshList')
  dialogVisible.value = false // 关闭弹窗
}
//   暴露方法
defineExpose({
  openDialog
})
</script>
<template>
  <!-- v-model="dialogVisible" 控制弹窗显示 -->
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '编辑分类' : '添加分类'"
    width="30%"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100px"
      style="padding: 10px 30px"
    >
      <el-form-item label="分类名称" prop="cate_name">
        <el-input
          v-model="formModel.cate_name"
          placeholder="请输入分类名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input
          v-model="formModel.cate_alias"
          placeholder="请输入分类别名"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit()"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
